using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Models;
using Constants;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace Data
{
    /// <summary>
    /// 数据库初始化器，用于初始化数据库和填充基础数据
    /// </summary>
    public static class DbInitializer
    {
        /// <summary>
        /// 初始化数据库并填充基础数据
        /// </summary>
        /// <param name="serviceProvider">服务提供者</param>
        public static async Task Initialize(IServiceProvider serviceProvider)
        {
            using var scope = serviceProvider.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();

            // 确保数据库已创建并应用所有迁移
            await context.Database.MigrateAsync();

            // 如果已有数据，则跳过初始化
            if (context.AppUsers.Any())
            {
                return;
            }

            // 创建默认Identity角色
            var adminRoleName = "Admin";
            var userRoleName = "User";

            // 创建管理员角色（如果不存在）
            if (!await roleManager.RoleExistsAsync(adminRoleName))
            {
                await roleManager.CreateAsync(new IdentityRole(adminRoleName));
            }
            // 创建普通用户角色（如果不存在）
            if (!await roleManager.RoleExistsAsync(userRoleName))
            {
                await roleManager.CreateAsync(new IdentityRole(userRoleName));
            }

            // 创建应用角色
            var adminAppRole = new Role { RoleName = adminRoleName };
            var userAppRole = new Role { RoleName = userRoleName };
            context.AppRoles.AddRange(adminAppRole, userAppRole);
            await context.SaveChangesAsync();

            // 创建系统默认权限
            var permissions = new[]
            {
                // 用户管理权限
                new Permission { PermissionName = $"{PermissionConstants.UsersPrefix}{PermissionOperations.View}" },
                new Permission { PermissionName = $"{PermissionConstants.UsersPrefix}{PermissionOperations.Create}" },
                new Permission { PermissionName = $"{PermissionConstants.UsersPrefix}{PermissionOperations.Edit}" },
                new Permission { PermissionName = $"{PermissionConstants.UsersPrefix}{PermissionOperations.Delete}" },
                
                // 角色管理权限
                new Permission { PermissionName = $"{PermissionConstants.RolesPrefix}{PermissionOperations.View}" },
                new Permission { PermissionName = $"{PermissionConstants.RolesPrefix}{PermissionOperations.Create}" },
                new Permission { PermissionName = $"{PermissionConstants.RolesPrefix}{PermissionOperations.Edit}" },
                new Permission { PermissionName = $"{PermissionConstants.RolesPrefix}{PermissionOperations.Delete}" }
            };
            context.Permissions.AddRange(permissions);
            await context.SaveChangesAsync();

            // 为管理员角色分配所有权限
            foreach (var permission in permissions)
            {
                context.RolePermissions.Add(new RolePermission
                {
                    RoleId = adminAppRole.RoleId,
                    PermissionId = permission.PermissionId
                });
            }

            // 为普通用户角色分配基本权限（查看权限和用户相关权限）
            var userPermissions = permissions.Where(p => 
                p.PermissionName.EndsWith(PermissionOperations.View.ToString()) ||
                p.PermissionName.StartsWith(PermissionConstants.UsersPrefix));

            foreach (var permission in userPermissions)
            {
                context.RolePermissions.Add(new RolePermission
                {
                    RoleId = userAppRole.RoleId,
                    PermissionId = permission.PermissionId
                });
            }

            // 创建默认管理员用户（Identity用户）
            var adminIdentityUser = new ApplicationUser 
            { 
                UserName = "admin@example.com",
                Email = "admin@example.com",
                FirstName = "Admin",
                LastName = "User",
                EmailConfirmed = true
            };
            await userManager.CreateAsync(adminIdentityUser, "Admin@123");
            await userManager.AddToRoleAsync(adminIdentityUser, adminRoleName);

            // 创建默认管理员用户（应用用户）
            var adminAppUser = new User { UserName = adminIdentityUser.UserName };
            context.AppUsers.Add(adminAppUser);
            await context.SaveChangesAsync();

            // 将应用管理员用户添加到应用管理员角色
            context.UserRoles.Add(new UserRole
            {
                UserId = adminAppUser.UserId,
                RoleId = adminAppRole.RoleId
            });

            await context.SaveChangesAsync();
        }
    }
} 